package vn.edu.ptithcm.pim.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.common.bean.PaginationObject;
import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.Paginations;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.ActivityLog;
import vn.edu.ptithcm.pim.dom.Project;
import vn.edu.ptithcm.pim.query.ActivityLogQuery;
import vn.edu.ptithcm.pim.service.ActivityLogService;
import vn.edu.ptithcm.pim.service.ProjectService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class ActivityLogController extends SimpleFormController {
	private ActivityLogService activityLogService;
	private UserService userService;
	private ProjectService projectService;

	Log log = LogFactory.getLog(ActivityLogController.class);

	public ActivityLogController() {
		super();
		setSessionForm(true);
		setCommandName("activityLogQuery");
		setCommandClass(ActivityLogQuery.class);
		setFormView(UrlConstants.ACTIVITY_LOG_URL);
		setSuccessView(UrlConstants.ACTIVITY_LOG_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ActivityLogQuery query = null;
		if (request.getSession().getAttribute("activityLogQuery") != null) {
			query = (ActivityLogQuery) request.getSession().getAttribute(
					"activityLogQuery");
		}
		if (query == null) {
			query = new ActivityLogQuery();
		}
		return query;
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	private void pagingActivityLog(HttpServletRequest request, Project project,
			ActivityLogQuery activityLogQuery) {
		try {
			PaginationObject paging = null;
			List<ActivityLog> activityLogs = new ArrayList<ActivityLog>();
			int total = 0;

			int currentPage = ParamUtil.getInteger(request,
					Paginations.CURRENT_PAGE_NUM, 1);
			int pageSize = ParamUtil.getInteger(request, Paginations.PAGE_SIZE,
					Paginations.ITEMS_PER_PAGE);

			total = activityLogService.countByQuery(project.getProjectid(),
					activityLogQuery);
			paging = new PaginationObject("activityLogPaging", total);

			paging.paging(currentPage, pageSize);

			int max = paging.getEndIndex() - paging.getStartIndex();
			activityLogs.addAll(activityLogService.findByQuery(
					project.getProjectid(), activityLogQuery, max,
					paging.getStartIndex()));

			request.setAttribute("activityLogs", activityLogs);
			request.setAttribute("paging", paging);
			request.setAttribute("total", total);

			log.info("results : " + activityLogs.size() + " activityLogs");
			log.info("total : " + total);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		log.info("ActivityLogController||onSubmit");
		ActivityLogQuery query = (ActivityLogQuery) command;
		String cmd = ParamUtil.getString(request, "cmd", "");

		int pnum = ParamUtil.getInteger(request, "pnum", 0);
		Project project = projectService.findByNumber(pnum);

		if ("searchActivityLogs".equals(cmd)) {
			log.info("cmd = searchActivityLogs");
			pagingActivityLog(request, project, query);

		} else if ("deleteActivityLogs".equals(cmd)) {
			log.info("cmd = deleteActivityLogs");
			if (query.getActivityLogIds().size() > 0) {
				for (int i = 0; i < query.getActivityLogIds().size(); ++i) {
					activityLogService.deleteById(new Long(query
							.getActivityLogIds().get(i)));
				}
				request.setAttribute("deletedItems", query.getActivityLogIds()
						.size());
				request.setAttribute("removeOK", true);
			}
			pagingActivityLog(request, project, query);
		}
		request.getSession().setAttribute("activityLogQuery", query);
		return showForm(request, response, errors);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		int pnum = ParamUtil.getInteger(request, "pnum", 0);
		Map<String, Object> bean = new HashMap<String, Object>();
		if (userService.isSignedIn(request)) {
			Project project = projectService.findByNumber(pnum);
			bean.put("project", project);
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put("tab", "activities");
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			boolean isAdmin = userService.isAdmin(loginName);
			bean.put("isAdmin", isAdmin);

			List<ActivityLog> activityLogs = new ArrayList<ActivityLog>();

			if (request.getAttribute("activityLogs") == null) {

				ActivityLogQuery query = null;

				if (isAdmin) {
					if (request.getSession().getAttribute("activityLogQuery") != null) {
						query = (ActivityLogQuery) request.getSession()
								.getAttribute("activityLogQuery");
					}
				}

				if (query == null) {
					query = new ActivityLogQuery();
				}

				pagingActivityLog(request, project, query);
			}

			activityLogs = (List<ActivityLog>) ParamUtil.getObject(request,
					"activityLogs", null);

			bean.put("paging", ParamUtil.getObject(request, "paging", null));
			bean.put("total", ParamUtil.getObject(request, "total", null));
			bean.put("pagingUrl", request.getRequestURL().toString() + "?pnum="
					+ pnum);
			bean.put("itemsPerPage", Paginations.ITEMS_PER_PAGE);
			bean.put("pnum", pnum);
			bean.put("activityLogs", activityLogs);
			bean.put("countList", activityLogs.size());

		} else {
			String redirectLink = UrlConstants.ACTIVITY_LOG_URL
					+ UrlConstants.HTM + "?pnum=" + pnum;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		request.setAttribute("bean", bean);
		return super.showForm(request, response, errors);
	}

	public ActivityLogService getActivityLogService() {
		return activityLogService;
	}

	public void setActivityLogService(ActivityLogService activityLogService) {
		this.activityLogService = activityLogService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

}
